package com.nie.mall.gateway.util;

import cn.hutool.json.JSONUtil;
import com.mall.common.domain.Result;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 响应工具类
 *
 * @author nie_cq
 * @date 2023/01/27
 */
@Component
public class ResponseUtil {

    /**
     * 返回mono
     *
     * @param response   响应
     * @param msg        消息
     * @param httpStatus http状态
     * @return {@code Mono<Void>}
     */
    public static Mono<Void>  returnMono(ServerHttpResponse response, String msg, HttpStatus httpStatus) {
        response.setStatusCode(httpStatus);
        Result<Object> fail = Result.fail(httpStatus.value(), msg, null);
        byte[] bytes = JSONUtil.parseObj(fail).toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        return response.writeWith(Mono.just(wrap));
    }

}
